<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col :span="4">
                <el-select v-model="selectedType" placeholder="选择申请类型" @change="handleFilterChange" class="filter-select">
                    <el-option label="所有类型" value=""></el-option>
                    <el-option label="旅行社" value="旅行社"></el-option>
                    <el-option label="定制官" value="定制官"></el-option>
                  </el-select>
            </el-col>
            <el-col :offset="142" :span="4">
                <el-input v-model="searchId" placeholder="输入用户ID" class="filter-input"></el-input>
            </el-col>
            <el-col  :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="tableData" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%">
                <el-table-column type="selection" />
                <el-table-column property='userId' label="用户ID" />
                <el-table-column property="applyCategory" label="申请类别 " />
                <el-table-column property="Qualification" label="资质证明文件">
                    <template #default="scope">
                        <!-- 判断是否有 PDF 链接 -->
                        <a v-if="scope.row.Qualification"
                           @click.prevent="handleDownloadPDF(scope.row.agencyId)"
                           href="#">
                            下载资质证明
                        </a>
                        <span v-else>暂无资质证明</span>
                    </template>
                </el-table-column>
                <el-table-column property="applyingTime" label="申请时间"  />
                <!-- 操作按钮 -->
                <el-table-column width="250" label="操作" algin="center">
                    <template #default="{ row }">
                        <!-- 驳回申请按钮，仅当状态为1（待审核）时可点击 -->
                        <el-button type="danger" @click="handleRejectApplication(row)"  link>
                          驳回申请
                        </el-button>
                        <!-- 通过审核按钮，仅当状态为1（待审核）时可点击 -->
                        <el-button type="success" @click="handleApproveApplication(row)" link>
                          通过审核
                        </el-button>
                      </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="paginationData.currentPage" v-model:pageSize="paginationData.pageSize"
                :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="3"
                @size-change="handleSizeChange" @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>

</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
const selectedType = ref('')
const searchId = ref()


// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
// 定义表格数据
const tableData = ref([])

// 定义 PaginationData 接口
interface PaginationData {
    currentPage: number;
    pageSize: number;
}
const paginationData = ref<PaginationData>({ currentPage: 1, pageSize: 5 });

const fetchApplicationData = async () => {
    try {
        const res = await axios.get('http://localhost:8088/applications/list');
        tableData.value = res.data;
    } catch (error) {
        console.log(error)
    }
}

const handleFilterChange = async () => {
    try {
        const response = await axios.get('http://localhost:8088/applications/filter', {
            params: {
                applyCategory: selectedType.value,
            },
        });
        tableData.value = response.data;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};

const handleSearch = async () => {
    try {
        console.log(searchId.value);
        const response = await axios.get('http://localhost:8088/applications/getById', {
            params: {
                userId: searchId.value,
            },
        });
        console.log(response.data);
        tableData.value = response.data;
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

// 下载 PDF 方法
const handleDownloadPDF = async (designerId) => {
    try {
        console.log(`开始请求签名 URL，designerId: ${designerId}`);

        // 请求后端接口获取签名 URL
        const response = await axios.get(`/getQualificationPath`, {
            params: { designerId, timestamp: new Date().getTime() }, // 加入时间戳确保每次请求都是新请求
        });

        console.log(`签名 URL 请求成功，返回数据:`, response.data);

        const signedUrl = response.data;  // 获取签名 URL
        console.log(`签名 URL：`, signedUrl);

        if (!signedUrl) {
            throw new Error("未能获得有效的签名 URL");
        }

        // 使用签名 URL 触发文件下载
        const a = document.createElement('a');
        a.href = signedUrl;
        a.download = 'qualification1.pdf';  // 可以指定下载的文件名
        document.body.appendChild(a);
        a.click();  // 触发下载
        document.body.removeChild(a);
        console.log("下载请求已发出");

    } catch (error) {
        console.error("下载失败：", error);
        ElMessage.error("文件下载失败，请稍后重试！");
    }
};

const handleRejectApplication = (row) => {
    // 驳回申请操作的逻辑
    if(row.applyCategory === '旅行社'){
        updateAgencyStatus(row.userId, 2); // 改为状态2表示驳回
    }else{
        updateDesignersStatus(row.userId, 2);
    }
    fetchApplicationData();
    console.log('Rejecting application:', row);
};

const handleApproveApplication = (row) => {
    // 通过审核操作的逻辑
    if(row.applyCategory === '旅行社'){
        updateAgencyStatus(row.userId, 0); // 改为状态1表示通过审核
    }else{
        updateDesignersStatus(row.userId, 0);
    }
    fetchApplicationData();
    console.log('Approving application:', row);
};

// 更新操作的函数
const updateAgencyStatus = async (userId, qualifyStatus) => {
  try {
    // 构建包含ID和新状态的请求体
    const requestBody = {
      userId,
      qualifyStatus,
    };

    const response = await axios.put(
      "http://localhost:8088/agencies/updateByUserId",
      requestBody
    );

    if (response.data) {
      ElMessage.success("操作成功");
    }
    return response.data;
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败");
    return null;
  }
};

const updateDesignersStatus = async (userId, qualifyStatus) => {
    try {
    // 构建包含ID和新状态的请求体
    const requestBody = {
      userId,
      qualifyStatus,
    };

    const response = await axios.put(
      "http://localhost:8088/servicedesigners/updateByUserId",
      requestBody
    );
    if (response.data) {
        ElMessage.success("操作成功");// 操作成功，给用户反馈
    }
    return response.data;
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败");
    return null;
  }
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
}

onMounted(() => {
    fetchApplicationData();
});
</script>

<style scoped>
.el-header {
    padding-left: 0px;
    padding-right: 0px;
}

.el-main {
    background-color: #F2F2F2;
}

.el-aside {
    background-color: #7162A7;
    width: auto;
}

.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}
.div-view-search{
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}



.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>